package libs;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Vector;
import java.nio.channels.*;
import javax.swing.JApplet;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.imageio.*;
import types.TBinContribution;


public class ImageProcess extends JApplet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public ImageProcess() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	public Image loadImage(String file){
		String f=file.substring(file.length()-3,file.length());
		Image img=null;
		if (f.toLowerCase().equals("bmp")) {
			try {
				img=LoadBitmap.loadbitmap(file,new JFrame());
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}else{
			img=getToolkit().getImage(file);
		}
	    MediaTracker mt = new MediaTracker(this);
	    mt.addImage(img, 0);
	    try {
	            mt.waitForID(0);
	    } catch (Exception exx) {
	    		// TODO: handle exception
	    }
	    return img;
		
	}
	
	public static Image InverseImage(Image imgx){
        int w=imgx.getWidth(null);
        int h=imgx.getHeight(null);
        int[] pixels=new int[w*h];
        int[] pixels1=new int[w*h];
        pixels=image2pixels(imgx, w, h);
		System.arraycopy(pixels, 0, pixels1, 0, w * h);
        for(int y = 0; y < h; y++)
        {
            for(int x = 0; x < w; x++)
                pixels1[y * w + x] = (int)(255 - (pixels[y * w + x] & 0xff));
        }
        Image img2=pixels2image(pixels1, w, h);
        return img2;
		
	}
	
    public static void copyFile(File in, File out) throws IOException {
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();
		// try {
		// inChannel.transferTo(0, inChannel.size(), outChannel);
		// } catch (IOException e) {
		try {
			// magic number for Windows, 64Mb - 32Kb)
			int maxCount = (64 * 1024 * 1024) - (32 * 1024);
			long size = inChannel.size();
			long position = 0;
			while (position < size) {
				position += inChannel.transferTo(position, maxCount, outChannel);
			}
		} catch (IOException e) {
			throw e;
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}


	public static void copyFile(String srFile, String dtFile){
		    try{
		      File f1 = new File(srFile);
		      File f2 = new File(dtFile);
		      InputStream in = new FileInputStream(f1);
		      
		      //For Append the file.
//		      OutputStream out = new FileOutputStream(f2,true);

		      //For Overwrite the file.
		      OutputStream out = new FileOutputStream(f2);

		      byte[] buf = new byte[1024];
		      int len;
		      while ((len = in.read(buf)) > 0){
		        out.write(buf, 0, len);
		      }
		      in.close();
		      out.close();
		      System.out.println("File copied.");
		    }
		    catch(FileNotFoundException ex){
		      System.out.println(ex.getMessage() + " in the specified directory.");
		      System.exit(0);
		    }
		    catch(IOException e){
		      System.out.println(e.getMessage());      
		    }
		  }

    // This method returns true if the specified image has transparent pixels
    public static boolean hasAlpha(Image image) {
        // If buffered image, the color model is readily available
        if (image instanceof BufferedImage) {
            BufferedImage bimage = (BufferedImage)image;
            return bimage.getColorModel().hasAlpha();
        }
    
        // Use a pixel grabber to retrieve the image's color model;
        // grabbing a single pixel is usually sufficient
         PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
        try {
            pg.grabPixels();
        } catch (InterruptedException e) {
        }
    
        // Get the image's color model
        ColorModel cm = pg.getColorModel();
        return cm.hasAlpha();
    }

	// This method returns a buffered image with the contents of an image
    public static BufferedImage toBufferedImage(Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage)image;
        }
    
        // This code ensures that all the pixels in the image are loaded
        //image = new ImageIcon(image).getImage();
    
        // Determine if the image has transparent pixels; for this method's
        // implementation, see e661 Determining If an Image Has Transparent Pixels
        //boolean hasAlpha = hasAlpha(image);
        boolean hasAlpha=false;
    
        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = null;
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        try {
            // Determine the type of transparency of the new buffered image
            int transparency = Transparency.OPAQUE;
            if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }
    
            // Create the buffered image
            GraphicsDevice gs = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gs.getDefaultConfiguration();
            bimage = gc.createCompatibleImage(
                image.getWidth(null), image.getHeight(null), transparency);
        } catch (HeadlessException e) {
            // The system does not have a screen
        }
    
        if (bimage == null) {
            // Create a buffered image using the default color model
            int type = BufferedImage.TYPE_INT_RGB;
            if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }
            bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
        }
    
        // Copy image to buffered image
        Graphics g = bimage.createGraphics();
    
        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();
    
        return bimage;
    }

    public static long getSimilarityCost(Image img1,Image img2){
    	Image retImg=imageAbsoluteDifference(img1, img2);
    	long ret=getPixelSum(retImg);
    	return ret;
    }
    
	public static void saveImageToJPG(Image imgx,String file_name) throws IOException{
    	try {
    		File file=new File(file_name);
    		ImageIO.write(toBufferedImage(imgx),"jpg",file);
		} catch (Exception e) {
			// TODO: handle exception
			
		}
	}
	
	public static Image NoiseReduction(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		temp=(int[][])dizi.clone();
		
		for (int i = 2; i < w-2; i++) {
			for (int j = 2; j < h-2; j++) {
				if (
						dizi[i-2][j-2]==255&&dizi[i-2][j-1]==255&&dizi[i-2][j]==255&&dizi[i-2][j+1]==255&&dizi[i-2][j+2]==255&&
						dizi[i+2][j-2]==255&&dizi[i+2][j-1]==255&&dizi[i+2][j]==255&&dizi[i+2][j+1]==255&&dizi[i+2][j+2]==255&&
						dizi[i-1][j-2]==255&&dizi[i][j-2]==255&&dizi[i+1][j-2]==255&&
						dizi[i-1][j+2]==255&&dizi[i][j+2]==255&&dizi[i+1][j+2]==255) {
					
					//JOptionPane.showMessageDialog(null, "yakalad�");
					temp[i-1][j]=255;
					temp[i-1][j-1]=255;
					temp[i-1][j+1]=255;
					
					temp[i][j]=255;
					temp[i][j-1]=255;
					temp[i][j+1]=255;
					
					temp[i+1][j]=255;
					temp[i+1][j-1]=255;
					temp[i+1][j+1]=255;
				}
			}
		}
		//point detection kernel architecture
		int[][] pkernel=new int[3][3];
		for (int i = 0; i < pkernel.length; i++) {
			for (int j = 0; j < pkernel.length; j++) {
				pkernel[i][j]=-1;
			}
		}
		pkernel[1][1]=8;
		
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				int sum=0;
				for (int k = -1; k < 2; k++) {
					for (int t = -1; t < 2; t++) {
						sum+=dizi[i+k][j+t]*pkernel[1+k][1+t];
					}
				}
				if (sum==-2040) {
					//writeln("sum:"+sum);
					temp[i][j]=255;
					
					
				}
				if (
						dizi[i-1][j-1]==255&&dizi[i-1][j]==255&&dizi[i-1][j+1]==255&&
						dizi[i][j-1]==255&&dizi[i][j]==0&&dizi[i][j+1]==255&&
						dizi[i+1][j-1]==255&&dizi[i+1][j]==255&&dizi[i+1][j+1]==255){
					temp[i][j]=255;
				}
//				if (
//						dizi[i-1][j-1]==255&&dizi[i-1][j]==255&&dizi[i-1][j+1]==255&&
//						dizi[i][j-1]==255&&dizi[i][j]==0&&dizi[i][j+1]==255&&
//						dizi[i+1][j-1]==255&&dizi[i+1][j]==0&&dizi[i+1][j+1]==255){
//					temp[i][j]=255;
//				}
				if (
						dizi[i-1][j-1]==255&&dizi[i-1][j]==0&&dizi[i-1][j+1]==255&&
						dizi[i][j-1]==255&&dizi[i][j]==0&&dizi[i][j+1]==255&&
						dizi[i+1][j-1]==255&&dizi[i+1][j]==0&&dizi[i+1][j+1]==255){
					temp[i][j]=255;
				}
//				if (
//						dizi[i-1][j-1]==255&&dizi[i-1][j]==255&&dizi[i-1][j+1]==255&&
//						dizi[i][j-1]==0&&dizi[i][j]==0&&dizi[i][j+1]==0&&
//						dizi[i+1][j-1]==255&&dizi[i+1][j]==255&&dizi[i+1][j+1]==255){
//					temp[i][j]=255;
//				}
				if (
						dizi[i-1][j-1]==0&&dizi[i-1][j]==255&&dizi[i-1][j+1]==255&&
						dizi[i][j-1]==255&&dizi[i][j]==0&&dizi[i][j+1]==255&&
						dizi[i+1][j-1]==255&&dizi[i+1][j]==255&&dizi[i+1][j+1]==0){
					temp[i][j]=255;
				}
				if (
						dizi[i-1][j-1]==255&&dizi[i-1][j]==255&&dizi[i-1][j+1]==0&&
						dizi[i][j-1]==255&&dizi[i][j]==0&&dizi[i][j+1]==255&&
						dizi[i+1][j-1]==0&&dizi[i+1][j]==255&&dizi[i+1][j+1]==255){
					temp[i][j]=255;
				}
				if (
						dizi[i-1][j-1]==0&&dizi[i-1][j]==0&&dizi[i-1][j+1]==0&&
						dizi[i][j-1]==0&&dizi[i][j]==255&&dizi[i][j+1]==0&&
						dizi[i+1][j-1]==0&&dizi[i+1][j]==0&&dizi[i+1][j+1]==0){
					temp[i][j-1]=255;
					temp[i][j+1]=255;
					temp[i-1][j]=255;
					temp[i+1][j]=255;
					temp[i-1][j-1]=255;
					temp[i-1][j+1]=255;
					temp[i+1][j-1]=255;
					temp[i+1][j+1]=255;
				}
			}
		}
		
		dizi=(int[][])temp.clone();
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static int medianKernel(int[] kernel){
		int buffer;
		for (int i = 0; i < kernel.length; i++) {
			for (int j = i; j < kernel.length; j++) {
				if (kernel[j]>kernel[i]) {
					buffer=kernel[j];
					kernel[j]=kernel[i];
					kernel[i]=buffer;
				}
			}
		}
		int mid=kernel.length/2;
		//System.out.println("mid point value:"+kernel[mid]);
		return kernel[mid];
	}
	
	public static void writeln(String s){
		System.out.println(s);
	}
	
	public static Image MedianFilter(Image imgx){
//		try {
			int w=imgx.getWidth(null);
			int h=imgx.getHeight(null);
			//yaz("w,h:"+w+":"+h);
			int[] kernel=new int[9];
			int dizi[][]=new int[w][h];
			int temp[][]=new int[w][h];
			dizi=imageToPixels255(imgx);
			temp=(int[][])dizi.clone();
			for (int i = 1; i < w-1; i++) {
				for (int j = 1; j < h-1; j++) {
					int f=0;
					for (int k = -1; k <=1; k++) {
						for (int t = -1; t <= 1; t++) {
							kernel[f]=dizi[i+k][j+t];
							f++;
						}
					}
					temp[i][j]=medianKernel(kernel);
				}
			}
			dizi=(int[][])temp.clone();
			Image ret_img=pixelsToImage255(dizi, w, h);
			return ret_img;
			
//		} catch (Exception e) {
//			// TODO: handle exception
//			System.out.println("median filtering de hata oldu");
			//return imgx;
//		}
	}
	
	public static Image MeanFilter(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int[] kernel=new int[9];
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		temp=(int[][])dizi.clone();
		int sum=0;
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				int f=0;
				for (int k = -1; k <=1; k++) {
					for (int t = -1; t <= 1; t++) {
						kernel[f]=dizi[i+k][j+t];
						sum+=kernel[f];
						f++;
					}
				}
				temp[i][j]=sum/9;
				sum=0;
			}
		}
		dizi=(int[][])temp.clone();
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static Image Erode(Image imgx,int[][] kernel){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				if (dizi[i-1][j-1]==kernel[0][0]&&dizi[i-1][j]==kernel[0][1]&&dizi[i-1][j+1]==kernel[0][2]&&
					dizi[i][j-1]==kernel[1][0]&&dizi[i][j]==kernel[1][1]&&dizi[i][j+1]==kernel[1][2]&&
					dizi[i+1][j-1]==kernel[2][0]&&dizi[i+1][j]==kernel[2][1]&&dizi[i+1][j+1]==kernel[2][2]) {
					
					temp[i][j]=0;
				}else{
					temp[i][j]=255;
				}
			}
		}
		dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static Image Erode(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
//		int[][] kernel=new int[3][3];
		
		dizi=imageToPixels255(imgx);
		for (int i = 2; i < w-2; i++) {
			for (int j = 2; j < h-2; j++) {
				if (dizi[i][j-1]==255&&
				dizi[i-1][j]==255&&dizi[i][j]==255&&dizi[i+1][j]==255&&
				dizi[i][j+1]==255) {
						
					temp[i][j]=255;
				}else{
					temp[i][j]=0;
				}

			}
		}
		dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static Image Subtract(Image img1,Image img2,int min,int max){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];
		
		int temp[][]=new int[w1][h1];
		
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		
		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
				if (fark>=min && fark<max) {
					temp[i][j]=fark;
				}else temp[i][j]=0;
				
//				temp[i][j]=fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
//				if (fark>0&&fark<=255) {
//					temp[i][j]=fark;	
//				}else{
//					temp[i][j]=0;
//				}
				//temp[i][j]=dizi1[i][j]-50;
			}
		}		
		return pixelsToImage255(temp, w1, h1);
	}
	
	public static Image imageAbsoluteDifference(Image img1,Image img2){
//		int w1=img1.getWidth(null);
//		int h1=img1.getHeight(null);
//		int dizi1[][]=new int[w1][h1];
//		int w2=img2.getWidth(null);
//		int h2=img2.getHeight(null);
//		int dizi2[][]=new int[w2][h2];		
//		int temp[][]=new int[w1][h1];
//		dizi1=imageToPixels255(img1);
//		dizi2=imageToPixels255(img2);
//		
//		int fark=0;
//		for (int i = 0; i < w1; i++) {
//			for (int j = 0; j < h1; j++) {
//				fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
//				//fark=(dizi1[i][j]-dizi2[i][j]);
//				if (fark>0&&fark<=255) {
//					temp[i][j]=fark;	
//				}else{
//					temp[i][j]=0;
//				}
//			}
//		}		
//		return pixelsToImage255(temp, w1, h1);
		return pixelsToImage255(imageAbsoluteDifferenceArray(img1,img2));
	}
	
	public static int[][] imageAbsoluteDifferenceArray(Image img1,Image img2){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];		
		int temp[][]=new int[w1][h1];
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		
		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
				temp[i][j]=fark;
//				if (fark>0&&fark<=255) {
//					temp[i][j]=fark;//*fark*fark;	
//				}else{
//					temp[i][j]=0;
//				}
			}
		}		
		return temp;
	}
	
	public static int[][] imageAbsoluteDifferenceArrayWithNormalization(Image img1,Image img2,int n,String type){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];		
		int temp[][]=new int[w1][h1];
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		if (type.equals("halogen")) {
			if(n>=0 && n<9){
				
			}else if(n==9){
				dizi2=normalizeArrayWithExposure(4.5/2.4,dizi2);
			}else if(n>=10 && n<19){
				dizi1=normalizeArrayWithExposure(4.5/2.4,dizi1);
				dizi2=normalizeArrayWithExposure(4.5/2.4,dizi2);			
			}else if(n==19){
				dizi2=normalizeArrayWithExposure(4.5/0.5,dizi2);
			}else{
				dizi1=normalizeArrayWithExposure(4.5/0.5,dizi1);
				dizi2=normalizeArrayWithExposure(4.5/0.5,dizi2);			
			}
		}
		if (type.equals("uv")) {
			if(n>=0 && n<29){
				
			}else if(n==29){
				dizi2=normalizeArrayWithExposure(9.6/3.1,dizi2);
			}else {
				dizi1=normalizeArrayWithExposure(9.6/3.1,dizi1);
				dizi2=normalizeArrayWithExposure(9.6/3.1,dizi2);			
			}
		}

		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
				temp[i][j]=fark;
			}
		}		
		return temp;
	}

	
	public static int[][] normalizeArrayWithExposure(double n, int[][] d) {
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				d[i][j]=(int)Math.round(d[i][j]*n);
			}
		}
		return d;
	}

	public static double getAbsoluteDifferenceImageExposureNormalized(Image img1, Image img2,int n,String type) {
		int[][] d=imageToPixels255(img1);
		int[][] dR=imageToPixels255(img2);
		
		if (type.equals("halogen")) {
			if(n>=0 && n<9){
				
			}else if(n==9){
				dR=normalizeArrayWithExposure(4.5/2.4,dR);
			}else if(n>=10 && n<19){
				d=normalizeArrayWithExposure(4.5/2.4,d);
				dR=normalizeArrayWithExposure(4.5/2.4,dR);				
			}else if(n==19){
				dR=normalizeArrayWithExposure(4.5/0.5,dR);
			}else{
				d=normalizeArrayWithExposure(4.5/0.5,d);
				dR=normalizeArrayWithExposure(4.5/0.5,dR);				
			}
		}
		if (type.equals("uv")) {
			if(n>=0 && n<29){
				
			}else if(n==29){
				dR=normalizeArrayWithExposure(9.6/3.1,dR);
			}else {
				d=normalizeArrayWithExposure(9.6/3.1,d);
				dR=normalizeArrayWithExposure(9.6/3.1,dR);				
			}
		}

		double ret=0;
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				double t=Math.abs(d[i][j]-dR[i][j]);
				ret+=t;
			}
		}
		double size=d.length*d[0].length;
		return Utils.formatDouble(ret/size);
	}

	public static double getAbsoluteDifferenceImage(Image img1, Image img2,int n,String type) {
		int[][] d=imageToPixels255(img1);
		int[][] dR=imageToPixels255(img2);
		double ret=0;
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				double t=Math.abs(d[i][j]-dR[i][j]);
				ret+=t;
			}
		}
		double size=d.length*d[0].length;
		return Utils.formatDouble(ret/size);
	}

	public static Image imageDifference(Image img1,Image img2){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];		
		int temp[][]=new int[w1][h1];
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
				if (fark>0&&fark<=255) {
					temp[i][j]=fark;	
				}else{
					temp[i][j]=0;
				}

			}
		}		
		return pixelsToImage255(temp, w1, h1);
	}

	public static int[][] imageDifferenceArray(Image img1,Image img2){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];		
		int temp[][]=new int[w1][h1];
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		
		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=dizi2[i][j]-dizi1[i][j];
				temp[i][j]=fark;
			}
		}		
		return temp;
	}
	
	public static int pixelTotal(Image img){
		int toplam=0;
		int[] temp=imageToPixels1D(img);
		for (int i = 0; i < temp.length; i++) {
			toplam+=temp[i];
		}
		return toplam;
	}
	
	public static int[] to1D(int[][] a){
		int w=a.length;
		int h=a[0].length;
		int[] b=new int[w*h];
		int k=0;
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				b[k]=a[i][j];
				k++;
			}
		}
		return b;
	}
	
	public static int[][] to2D(int[] a,int w,int h){
		int k=0;
		int[][] temp=new int[w][h];
		
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				temp[i][j]=a[k];
				k++;
			}
		}
		return temp;
	}
	
	public static int[] Erode(int[] diz,int w,int h){
		int[][] dizi=new int[w][h];
		dizi=to2D(diz, w, h);
		int temp[][]=new int[w][h];
		temp=(int[][])dizi.clone();
		int[] fiz=new int[w*h];
		for (int i = 2; i < w-2; i++) {
			for (int j = 2; j < h-2; j++) {
				if (dizi[i][j-1]==255&&
				dizi[i-1][j]==255&&dizi[i][j]==255&&dizi[i+1][j]==255&&
				dizi[i][j+1]==255) {
						
					temp[i][j]=255;
				}else{
					temp[i][j]=0;
				}

			}
		}
		dizi=temp;
		fiz=to1D(dizi);
		return fiz;
	}
	
	public static Image Dilate(Image imgx,int[][] kernel){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				if (dizi[i-1][j-1]==kernel[0][0]||dizi[i-1][j]==kernel[0][1]||dizi[i-1][j+1]==kernel[0][2]||
						dizi[i][j-1]==kernel[1][0]||dizi[i][j]==kernel[1][1]||dizi[i][j+1]==kernel[1][2]||
						dizi[i+1][j-1]==kernel[2][0]||dizi[i+1][j]==kernel[2][1]||dizi[i+1][j+1]==kernel[2][2]) {
					temp[i][j]=0;
				}else{
					temp[i][j]=255;
				}
			}
		}
		dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static Image Dilate(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		int[][] kernel=new int[3][3];
		dizi=imageToPixels255(imgx);
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				if (dizi[i-1][j-1]==kernel[0][0]||dizi[i-1][j]==kernel[0][1]||dizi[i-1][j+1]==kernel[0][2]||
						dizi[i][j-1]==kernel[1][0]||dizi[i][j]==kernel[1][1]||dizi[i][j+1]==kernel[1][2]||
						dizi[i+1][j-1]==kernel[2][0]||dizi[i+1][j]==kernel[2][1]||dizi[i+1][j+1]==kernel[2][2]) {
					temp[i][j]=0;
				}else{
					temp[i][j]=255;
				}
			}
		}
		dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
	}
	
	public static Image kernelFilter(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
//		int temp[][]=new int[w][h];
		int kw=15;
		int kh=15;
		int med=kw/2;
		
		int[][] kernel=new int[kw][kh];
		for (int i = 2; i < kw-2; i++) {
			for (int j = 2; j < kh-2; j++) {
				kernel[i][j]=255;
			}
		}
		
		dizi=imageToPixels255(imgx);
		for (int i = med; i < w-med; i++) {
			for (int j = med; j < h-med; j++) {
				if (dizi[i-med][j-med]==0&&dizi[i-med][j+med]==0&&dizi[i+med][j-med]==0&&dizi[i+med][j+med]==0
						&&dizi[i][j]==255&&dizi[i-1][j-1]==255&&dizi[i-1][j+1]==255&&dizi[i+1][j-1]==255&&dizi[i+1][j+1]==255){
					for (int k = 0; k < med; k++) {
						for (int m = 0; m < med; m++) {
							if (dizi[i+k][j+m]==255) {
								dizi[i+k][j+m]=0;
							}
						
						}
					}
					//writeln("bulundu:"+i+","+j);
				}
			}
		}
		//dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
		
	}
	
	public static Image GrowChar(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				temp[i][j]=255;
			}
		}
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				if (dizi[i-1][j-1]==0) {
					temp[i-1][j-1]=0;
					temp[i][j-1]=0;
					temp[i][j]=0;
				}
			}
		}
		Image ret_img=pixelsToImage255(temp, w, h);
		return ret_img;
	}
	
	public static Image ShrinkChar(Image imgx){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				temp[i][j]=dizi[i][j];
			}
		}
		for (int i = 2; i < w-2; i++) {
			for (int j = 2; j < h-2; j++) {
				if (dizi[i][j-2]==255&&dizi[i][j-1]==0&&dizi[i][j]==0&&dizi[i][j+1]==255) {
					temp[i][j-1]=0;
					temp[i][j]=255;
				}
			}
		}
		Image ret_img=pixelsToImage255(temp, w, h);
		return ret_img;
	}
	
	public static Image RemoveNoise(Image imgx,int[][] kernel){
		int w=imgx.getWidth(null);
		int h=imgx.getHeight(null);
		int dizi[][]=new int[w][h];
		int temp[][]=new int[w][h];
		dizi=imageToPixels255(imgx);
		for (int i = 1; i < w-1; i++) {
			for (int j = 1; j < h-1; j++) {
				if (dizi[i-1][j-1]==kernel[0][0]||dizi[i-1][j]==kernel[0][1]||dizi[i-1][j+1]==kernel[0][2]||
						dizi[i][j-1]==kernel[1][0]||dizi[i][j]==kernel[1][1]||dizi[i][j+1]==kernel[1][2]||
						dizi[i+1][j-1]==kernel[2][0]||dizi[i+1][j]==kernel[2][1]||dizi[i+1][j+1]==kernel[2][2]) {
					temp[i][j]=0;
				}else{
					temp[i][j]=255;
				}
			}
		}
		dizi=temp;
		Image ret_img=pixelsToImage255(dizi, w, h);
		return ret_img;
		
	}
	
	public static int[] image2pixels(Image image,int width,int height) {
      	int picsize=width*height;
    	int pix [] = new int[picsize];
    	int fpix [] = new int[picsize];
      	PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, width, height, pix, 0, width);
      	try {
      		pixelgrabber.grabPixels();
      	} catch (InterruptedException interruptedexception) {
      		interruptedexception.printStackTrace();
      	}
      	for(int i = 0; i < pix.length; i++)
        {
            int r = pix[i] >> 16 & 0xff;
            int g = pix[i] >> 8 & 0xff;
            int b = pix[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpix[i]=y;
        }
      	
      	return fpix;
    }

	public static int[] imageTo1Dpixels255(Image image,int width,int height) {
      	int picsize=width*height;
    	int pix [] = new int[picsize];
    	int fpix [] = new int[picsize];
      	PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, width, height, pix, 0, width);
      	try {
      		pixelgrabber.grabPixels();
      	} catch (InterruptedException interruptedexception) {
      		interruptedexception.printStackTrace();
      	}
      	for(int i = 0; i < pix.length; i++)
        {
            int r = pix[i] >> 16 & 0xff;
            int g = pix[i] >> 8 & 0xff;
            int b = pix[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpix[i]=y;
        }
      	
      	return fpix;
    }

	public static double[] image2pixelsD(Image image,int width,int height) {
      	int picsize=width*height;
    	int pix [] = new int[picsize];
    	int fpix [] = new int[picsize];
      	double pixd [] = new double[picsize];

      	PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, width, height, pix, 0, width);
      	try {
      		pixelgrabber.grabPixels();
      	} catch (InterruptedException interruptedexception) {
      		interruptedexception.printStackTrace();
      	}
        
      	for(int i = 0; i < pix.length; i++)
        {
            int r = pix[i] >> 16 & 0xff;
            int g = pix[i] >> 8 & 0xff;
            int b = pix[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpix[i]=y;
            pixd[i]=(double)fpix[i];
        }
       	return pixd;
    }
	
    public static Image pixels2image(int aix[],int width,int height) {
    	int[] ai=new int[width*height];
    	for (int i = 0; i < aix.length; i++) {
	   		ai[i] = (0xff000000 | aix[i] << 16 | aix[i] << 8 | aix[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
        return imG;
    }
    
    public static Image pixels2image255(int aix[],int width,int height) {
    	int size=aix.length;
    	int[] ai=new int[size];
    	for (int i = 0; i < aix.length; i++) {
	   		ai[i] = (0xff000000 | aix[i] << 16 | aix[i] << 8 | aix[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
        return imG;
    }
	
    public static Image pixels2image_d(double aix[],int width,int height) {
    	int[] a=new int[width*height];
    	int[] ai=new int[width*height];
    	for (int i = 0; i < aix.length; i++) {
	   		a[i]=(int)aix[i];
    		ai[i] = (0xff000000 | a[i] << 16 | a[i] << 8 | a[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
        //Image imG =createImage(new MemoryImageSource(width, height, ai, 0, width));
        return imG;
    }

    public static Image pixels2imaged(double[] aid,double[] comp,int width,int height) {
    	int size=width*height;
    	int[] ai=new int[size];
    	int[] pix=new int[size];
    	double dpix[]=new double[size];
    	double[] pixR=new double[size];
    	double[] pixC=new double[size];
     	for (int i = 0; i < aid.length; i++) {
    		pixR[i]=Math.pow(aid[i],2);
    		pixC[i]=Math.pow(comp[i],2);
    		dpix[i]=Math.sqrt(pixR[i]+pixC[i]);
		}
    	
    	double d_enb=0;
    	double d_enk=0;
    	for (int i = 0; i < dpix.length; i++) {
			if (dpix[i]<1) {
	    		if (d_enb<dpix[i]) {
					d_enb=dpix[i];
				}
				if (d_enk>dpix[i]) {
					d_enk=dpix[i];
				}
				
			}
		}
		//scale the range of min max value to 0..255 gray pixel values
    	System.out.println("enb:"+d_enb);
    	System.out.println("enk:"+d_enk);
    	double deltaX=d_enb-d_enk;
    	double kX=255.0/deltaX;
    	double nX=-d_enk*kX;
    	for (int i = 0; i < dpix.length; i++) {
			pix[i]=(int)(dpix[i]*kX+nX);
	   		ai[i] = (0xff000000 | pix[i] << 16 | pix[i] << 8 | pix[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
        //Image imG =createImage(new MemoryImageSource(width, height, ai, 0, width));
        return imG;
    }

    public static Image pixels2imaged_log(double[] aid,double[] comp,int width,int height) {
    	int size=width*height;
    	int[] ai=new int[size];
    	int[] pix=new int[size];
    	double dpix[]=new double[size];
    	double[] pixR=new double[size];
    	double[] pixC=new double[size];
     	for (int i = 0; i < aid.length; i++) {
    		pixR[i]=Math.pow(aid[i],2);
    		pixC[i]=Math.pow(comp[i],2);
    		dpix[i]=Math.log(Math.sqrt(pixR[i]+pixC[i]));
		}
    	
    	double d_enb=0;
    	double d_enk=0;
    	for (int i = 0; i < dpix.length; i++) {
	    		if (d_enb<dpix[i]) {
					d_enb=dpix[i];
				}
				if (d_enk>dpix[i]) {
					d_enk=dpix[i];
				}
				
		}
		//scale the range of min max value to 0..255 gray pixel values
    	System.out.println("enb:"+d_enb);
    	System.out.println("enk:"+d_enk);
    	double deltaX=d_enb-d_enk;
    	double kX=255.0/deltaX;
    	double nX=-d_enk*kX;
    	for (int i = 0; i < dpix.length; i++) {
			pix[i]=(int)(dpix[i]*kX+nX);
	   		ai[i] = (0xff000000 | pix[i] << 16 | pix[i] << 8 | pix[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
        //Image imG =createImage(new MemoryImageSource(width, height, ai, 0, width));
        return imG;
    	
    }
    
    public static Image pixels2imaged_phase(double[] aid,double[] comp,int width,int height) {
    	int size=width*height;
    	int[] ai=new int[size];
    	int[] pix=new int[size];
    	double dpix[]=new double[size];
     	for (int i = 0; i < aid.length; i++) {
    		dpix[i]=Math.atan((comp[i]/aid[i]));
		}
    	
    	double d_enb=0;
    	double d_enk=0;
    	for (int i = 0; i < dpix.length; i++) {
	    		if (d_enb<dpix[i]) {
					d_enb=dpix[i];
				}
				if (d_enk>dpix[i]) {
					d_enk=dpix[i];
				}
				
		}
		//scale the range of min max value to 0..255 gray pixel values
    	System.out.println("enb:"+d_enb);
    	System.out.println("enk:"+d_enk);
    	double deltaX=d_enb-d_enk;
    	double kX=255.0/deltaX;
    	double nX=-d_enk*kX;
    	for (int i = 0; i < dpix.length; i++) {
			pix[i]=(int)(dpix[i]*kX+nX);
	   		ai[i] = (0xff000000 | pix[i] << 16 | pix[i] << 8 | pix[i]);
		}
        Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(width, height, ai, 0, width));
       //Image imG =createImage(new MemoryImageSource(width, height, ai, 0, width));
       return imG;
    }

	public static int[][] imageToPixels255(Image img){
        MediaTracker mt = new MediaTracker(null);
        mt.addImage(img, 0);
        try {
            mt.waitForID(0);
        } catch (Exception e) {
    		// TODO: handle exception
    	}
        
        int w = img.getWidth(null);
        int h = img.getHeight(null);
        //System.out.println("w:"+w+" h:"+h);
        int pixels[] = new int[w * h];
        int fpixels[] = new int[w * h];
        int dpixel[][] = new int[w][h];
        PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
        try {
            pg.grabPixels();
    	} catch (Exception e) {
    		// TODO: handle exception
    	}
      	
    	for(int i = 0; i < pixels.length; i++)
        {
            int r = pixels[i] >> 16 & 0xff;
            int g = pixels[i] >> 8 & 0xff;
            int b = pixels[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpixels[i]=y;
        }
        
    	int k=0;
    	for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				dpixel[j][i]=fpixels[k];
				k++;
			}
		}
		return dpixel;
	}
	
	public static int[] imageToPixels1D(Image img){
        MediaTracker mt = new MediaTracker(null);
        mt.addImage(img, 0);
        try {
            mt.waitForID(0);
        } catch (Exception e) {
    		// TODO: handle exception
    	}
        
        int w = img.getWidth(null);
        int h = img.getHeight(null);
        //System.out.println("w:"+w+" h:"+h);
        int pixels[] = new int[w * h];
        int fpixels[] = new int[w * h];
//        int dpixel[][] = new int[w][h];
        PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
        try {
            pg.grabPixels();
    	} catch (Exception e) {
    		// TODO: handle exception
    	}
      	
    	for(int i = 0; i < pixels.length; i++)
        {
            int r = pixels[i] >> 16 & 0xff;
            int g = pixels[i] >> 8 & 0xff;
            int b = pixels[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpixels[i]=y;
        }
		return fpixels;
	}
	
	public static Image cropImage(Image img,Rectangle rect){
//		int px=rect.x;
//		int py=rect.y;
//		int w=rect.width;
//		int h=rect.height;
//		Image temp=snap_image(im, x, y, wx, hy)
//		try {
//			int[][] pixels2d=imageToPixels255(img);
//			
//		} catch (Exception e) {
//			// TODO: handle exception
//		}
		return snap_image(img, rect.x, rect.y, rect.width, rect.height);
	}
	
	public static int[][] imageToPixels(Image img){
        MediaTracker mt = new MediaTracker(null);
        mt.addImage(img, 0);
        try {
            mt.waitForID(0);
        } catch (Exception e) {
    		// TODO: handle exception
    	}
        
        int w = img.getWidth(null);
        int h = img.getHeight(null);
        //System.out.println("w:"+w+" h:"+h);
        int pixels[] = new int[w * h];
        int fpixels[] = new int[w * h];
        int dpixel[][] = new int[w][h];
        PixelGrabber pg = new PixelGrabber(img, 0, 0, w, h, pixels, 0, w);
        try {
            pg.grabPixels();
    	} catch (Exception e) {
    		// TODO: handle exception
    	}
      	
    	for(int i = 0; i < pixels.length; i++)
        {
            int r = pixels[i] >> 16 & 0xff;
            int g = pixels[i] >> 8 & 0xff;
            int b = pixels[i] >> 0 & 0xff;
            int y = (int)(0.33000000000000002D * (double)r + 0.56000000000000005D * (double)g + 0.11D * (double)b);
            fpixels[i]=y;
        }
        
    	int k=0;
    	for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				dpixel[j][i]=pixels[k];
				k++;
			}
		}
		return dpixel;
	}
		//ai[i] = (0xff000000 | aix[i] << 16 | aix[i] << 8 | aix[i]);
	
	public static Image pixelsToImage255(int dizi[][],int w,int h){
        int ai[]=new int[w*h];
        int aix[]=new int[w*h];
        int k=0;
        for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				ai[k]=dizi[j][i];
				aix[k] = (0xff000000 | ai[k] << 16 | ai[k] << 8 | ai[k]);
				k++;
			}
		}
		Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, aix, 0, w));
        return imG;		
	}
	
	public static Image pixelsToImage255(int dizi[][]){
        int w=dizi.length;
        int h=dizi[0].length;
		int ai[]=new int[w*h];
        int aix[]=new int[w*h];
        int k=0;
        for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
//				if (dizi[j][i]>255) {
//					dizi[j][i]=255;
//				}
				ai[k]=dizi[j][i];
				aix[k] = (0xff000000 | ai[k] << 16 | ai[k] << 8 | ai[k]);
				k++;
			}
		}
		Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, aix, 0, w));
        return imG;		
	}
	
	public static Image pixelsToImage255_eski(int dizi[][]){
        int w=dizi.length;
        int h=dizi[0].length;
		int ai[]=new int[w*h];
        int aix[]=new int[w*h];
        int k=0;
        for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				ai[k]=dizi[j][i];
				aix[k] = (0xff000000 | ai[k] << 16 | ai[k] << 8 | ai[k]);
				k++;
			}
		}
		Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, aix, 0, w));
        return imG;		
	}

	public static Image pixelsToImage(int dizi[][],int w,int h){
        int ai[]=new int[w*h];
        int k=0;
        for (int i = 0; i < h; i++) {
			for (int j = 0; j < w; j++) {
				ai[k]=dizi[j][i];
				k++;
			}
		}
    	//return Toolkit.getDefaultToolkit().createImage(memoryimagesource);
		Image imG =Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(w, h, ai, 0, w));
        return imG;		
	}
	
	public static Image snap_image(Image im,int x,int y,int wx,int hy){
//        MediaTracker mt = new MediaTracker(null);
//        mt.addImage(im, 0);
//        try {
//            mt.waitForID(0);
//        } catch (Exception e) {
//    		// TODO: handle exception
//    	}
		Image imG=null;
        //try {
            int w = im.getWidth(null);
            int h = im.getHeight(null);
            int pixels[][]=new int[w][h];
            pixels=imageToPixels(im);
            int dpix[][]=new int[wx][hy];
            for (int i = y; i < y+hy; i++) {
    			for (int j = x; j < x+wx; j++) {
    				dpix[j-x][i-y]=pixels[j][i];
    			}
    		}
            imG =pixelsToImage(dpix,wx,hy);
			
		//} catch (Exception e) {
			//throw;
			// TODO: handle exception
			//yaz("hata oldu "+e);
		//}
        return imG;
	}
	
	public static void yaz(String str){
		System.out.println(str);
	}
	
	public static int GetMin(int[][] dizi){
		int min = dizi[0][0];
		for (int i = 0; i < dizi.length; i++) {
			for (int j = 0; j < dizi[0].length; j++) {
				if (dizi[i][j]<min) {
					min=dizi[i][j];
				}
			}
		}
		return min;
	}
	
	public static int GetMax(int[][] dizi){
		int max = dizi[0][0];
		for (int i = 0; i < dizi.length; i++) {
			for (int j = 0; j < dizi[0].length; j++) {
				if (dizi[i][j]>max) {
					max=dizi[i][j];
				}
			}
		}
		return max;
	}
	
	public static int GetMax(int[] dizi){
		int max = dizi[0];
		for (int i = 0; i < dizi.length; i++) {
				if (dizi[i]>max) {
					max=dizi[i];
				}
		}
		return max;
	}
	
	public static int GetMin(int[] dizi){
		int max = dizi[0];
		for (int i = 0; i < dizi.length; i++) {
				if (dizi[i]>max) {
					max=dizi[i];
				}
		}
		return max;
	}
	
	public static Point GetMaxHough(int[][] dizi,int w,int h){
		int max = dizi[0][0];
		Point p=new Point();
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				if (dizi[i][j]>max) {
					max=dizi[i][j];
					p.x=i;
					p.y=j;
				}
			}
		}
		return p;
	}
	
	public static void normalizeMinMax(int[][] dizi){

	  	int min, max;

	  	min = GetMin(dizi);
	  	max = GetMax(dizi);

		if (max!=min)
		{
	  		for(int i = 0 ; i < dizi.length; i++){
	  			for (int j = 0; j < dizi[0].length; j++) {
		  			dizi[i][j]=((dizi[i][j]-min)*255)/(max-min);					
				}
			}
		}else{
	  		for(int i = 0 ; i < dizi.length; i++){
	  			for (int j = 0; j < dizi[0].length; j++) {
		  			dizi[i][j]=0;					
				}
			}
		}
		
	}
	
	public static Point[] sortMaxVal(int[][] gelen,int number){
		int w=gelen.length;
		int h=gelen[0].length;
		
		int[][] dizi=new int[w][h];
		dizi=(int[][])gelen.clone();
		int max=0;
		int x=0;
		int y=0;
		Point[] p=new Point[number];
		for (int t = 0; t < number; t++) {
			for (int i = 0; i < w; i++) {
				for (int j = 0; j < h; j++) {
					if (dizi[i][j]>max) {
						max=dizi[i][j];
						x=i;
						y=j;
					}
				}
			}
			dizi[x][y]=0;
			Point pnt=new Point();
			pnt.x=x;
			pnt.y=y;
			max=0;
			p[t]=pnt;
		}
		return p;
	}
	
    public static Image LineHoughTrans(Image T)
    {
    	int w = T.getWidth(null);
    	int h = T.getHeight(null);
    	int[][] pix=new int[w][h];
    	pix=imageToPixels255(T);

    	int r;

    	double tet;

    	int rMax = (int)(Math.sqrt((w/2*w/2) +(h/2*h/2)));///2);
    	//hough dizisi rt
     	int[][] rt=new int[361][rMax+1];
    	for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
    			int a=pix[i][j];
    			//e�er siyah bir nokta ise hough trans a bak de�ilse taband�r ge�
    			if (a==0) {
    				for(int t=0; t<360; t++)
    				{
    					tet = Math.toRadians(t);
    					r=Math.abs((int)(i*Math.cos(tet)+j*Math.sin(tet)));
    					//System.out.println("t,r:"+t+","+r);
    					if (r<rMax) {
        					rt[t][r]++;//habire artt�r							
						}
    				}
				}
				
			}
		}
    	Point[] pt=new Point[2];
    	pt[0]=new Point();
    	pt[1]=new Point();
    	pt=sortMaxVal(rt, 2);
    	for (int i = 0; i < 2; i++) {
        	for (int x = 0; x < w; x++) {
    			int ro=pt[i].y;
    			int t=pt[i].x;
    			int y=Math.abs((int)(ro-x*Math.cos(Math.toRadians(t))/Math.sin(Math.toDegrees(t))));
        		if (y<h) {
            		pix[x][y]=0;
    			}    		
    		}
			
		}
    	Image img2=pixelsToImage255(pix,w,h);
//    	Image zet=pixelsToImage255(rt,360,rMax);
    	
    	return img2;
    }
	
	public static Image ScaleImage(Image imgx,int t){
        System.out.println("t:"+t);
        int w = imgx.getWidth(null);
        int h = imgx.getHeight(null);
        System.out.println("awidthx:"+w);
        System.out.println("aheightx:"+h);
        int pixels[][]=new int[w][h];
        int w1=w/t;
        int h1=h/t;
        System.out.println("widthx:"+w1);
        System.out.println("heightx:"+h1);

        int pix[][]=new int[w1][h1];
        pixels=imageToPixels(imgx);
        int k=0;
        int q=0;
        int x=0;
        int y=0;
        for (int i = 0; i < w-1; i++) {
			for (int j = 0; j < h-1; j++) {
				if (k==t) {
					k=0;
					pix[x][y]=pixels[i][j];
					System.out.println("pix[:"+x+"]["+y+"]:"+pixels[x][y]);
					y++;					
					if (y==h1) {
						y=0;
						k=0;
					}
				}else{
					k++;
				}
				
			}
			if (q==t) {
				q=0;
				x++;
			}else{
				q++;
			}
			
		}
        Image ret=pixelsToImage(pix, w1, h1);
        System.out.println("width:"+ret.getWidth(null));
        System.out.println("height:"+ret.getHeight(null));
        return ret;
	}

	public static double[][] fill_kernel(double sigma){
		double[][] dax=new double[25][25];
		
		for (int i = 0; i < 25; i++) {
			for (int j = 0; j < 25; j++) {
				dax[i][j]=Math.exp(-(Math.pow((i-12),2)+Math.pow((j-12),2))/(2*sigma*sigma));
				//System.out.println("kernel["+i+"]["+j+"]="+dax[i][j]);
			}
		}
		return dax;
	}
	
	public static Image gfilter_spatial(Image img,double sigma){
		int w=img.getWidth(null);
		int h=img.getHeight(null);
		System.out.println("width:"+w);
		System.out.println("height:"+h);
		
		int[][] aim=new int[w][h];
		int[][] xim=new int[w][h];
		double[][] gkernel=new double[25][25];
		gkernel=fill_kernel(sigma);
		
		int[] temp=new int[w*h];
		temp=image2pixels(img,w,h);
		int kl=0;
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				aim[i][j]=temp[kl];
				kl++;
			}
		}
		
		double sum=0.0d;//sum of the gaussian kernel indices
		for (int i = 0; i < 25; i++) {
			for (int j = 0; j < 25; j++) {
				sum+=gkernel[i][j];
			}
		}
		System.out.println("kernel sum:"+sum);
		int val=0;
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				//kernel grid manipulation
				int zsum=0;
				for (int k = 0; k < 25; k++) {
					for (int z = 0; z < 25; z++) {
						/*
						if (i-12<0||j-12<0||i+12>255||j+12>255) {
							val=0;
						}else{
							val=aim[i][j];
						}
						*/
						if (i+k-12<0||j+z-12<0||i+k-12>w-1||j+z-12>h-1) {
							val=0;
						}else{
							val=aim[i][j];
							//val=aim[i+k-12][j+z-12];
						}
						//val=aim[i+k-12][j+z-12];
						zsum+=gkernel[k][z]*val;
						
					}
				}
				//System.out.println("zsum:"+zsum);

				xim[i][j]=(int)(zsum/sum);
			}
		}
		
		kl=0;
		for (int i = 0; i < w; i++) {
			for (int j = 0; j < h; j++) {
				temp[kl]=xim[i][j];
				kl++;
			}
		}
		Image dmg;
		dmg=pixels2image(temp,w,h);
		
		return dmg;
		
		
	}

	@SuppressWarnings("unchecked")
	public int[] getDifferentPixels(Image img1, Image img2, int min1,int min2,int max1,int max2,JList list) {
		String str="";
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[]=new int[w1*h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[]=new int[w2*h2];
		
//		int temp[][]=new int[w1][h1];
		
		dizi1=imageToPixels1D(img1);
		dizi2=imageToPixels1D(img2);
		
//		Vector<Integer> ret=new Vector<Integer>();
		Vector listdata=new Vector();
		for (int i = 0; i < list.getModel().getSize(); i++) {
			listdata.add(list.getModel().getElementAt(i));
		}
		//listdata=list.
		int n1=0;
		int n2=0;
		int sum=0;
		str="starting new comparison";
		yaz(str);
		listdata.add(str);
		for (int i = 0; i <= 255; i++) {
			n1=n2=0;
			for (int j = 0; j < dizi1.length; j++) {
				if (dizi1[j]==i) {
					n1++;
				}
			}
			for (int j = 0; j < dizi2.length; j++) {
				if (dizi2[j]==i) {
					n2++;
				}
			}
			yaz("pixel:"+i+" n1:"+n1+" n2:"+n2);
			if((n1>min1)&&(n1<min2)&&(n2>max1)&&(n2<max2)){
				str="******* detect pixel:"+i+" n1:"+n1+" n2:"+n2;
				yaz(str);
				listdata.add(str);
				sum++;
			}
		}		
		str="total:"+sum;
		yaz(str);
		listdata.add(str);
		list.setListData(listdata);
		list.ensureIndexIsVisible(listdata.size()-1);
		//return pixelsToImage255(temp, w1, h1);
		return null;
	}

	@SuppressWarnings("unchecked")
	public Vector<Integer> getDifferentPixelsByRatio(Image img1, Image img2, double ratio1,double ratio2,JList list) {
		String str="";
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[]=new int[w1*h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[]=new int[w2*h2];
		
		//int temp[][]=new int[w1][h1];
		
		dizi1=imageToPixels1D(img1);
		dizi2=imageToPixels1D(img2);
		
//		Vector<Integer> ret=new Vector<Integer>();
		
		Vector listdata=new Vector();
		for (int i = 0; i < list.getModel().getSize(); i++) {
			listdata.add(list.getModel().getElementAt(i));
		}
		
		int n1=0;
		int n2=0;
		int sum=0;
		str="starting new comparison";
		yaz(str);
		listdata.add(str);
		for (int i = 0; i <= 255; i++) {
			n1=n2=0;
			for (int j = 0; j < dizi1.length; j++) {
				if (dizi1[j]==i) {
					n1++;
				}
			}
			for (int j = 0; j < dizi2.length; j++) {
				if (dizi2[j]==i) {
					n2++;
				}
			}
			if (n1==0) {
				n1=1;
			}
			double ratio=(n2*1.0)/(n1*1.0);
			if (ratio>=ratio1&&ratio<ratio2) {
				str="******* detect pixel:"+i+" n1:"+n1+" n2:"+n2;
				yaz(str);
				listdata.add(str);
				sum++;				
			}
		}		
		str="total:"+sum;
		yaz(str);
		listdata.add(str);
		list.setListData(listdata);
		list.ensureIndexIsVisible(listdata.size()-1);
		return null;
	}
	
	public static double[] getQuantizedPixelMagnitudeFromImage(Image _image,int qLevel){
		int[] dizi=imageToPixels1D(_image);
		int interval=qLevel;
		double[] ret=new double[255/interval+1];
		for (int i = 0; i < dizi.length; i++) {
			int a=dizi[i]/interval;
			ret[a]++;
		}
		return ret;
	}
	
	public static String getQuantizedPixelMagnitudeFromImageAsString(Image _image,int qLevel){
//		int[] dizi=imageToPixels1D(_image);
//		int interval=qLevel;
//		int[] ret=new int[255/interval+1];
//		String str="";
//		for (int i = 0; i < dizi.length; i++) {
//			int a=dizi[i]/interval;
//			ret[a]++;
//		}
//		for (int i = 0; i < ret.length; i++) {
//			str+=ret[i]+";";
//		}
		int n=256/qLevel;
		int t1=0;
		int t2=0;
		String str="";
		for (int i = 0; i < n; i++) {
			t1=i*5;
			t2=t1+5;
			long totalPixel=ImageProcess.getPixelCount(_image, t1, t2);
			//println(t1+"-"+t2+" pixel toplami�:"+totalPixel);
			//writeln(t1+"-"+t2+" pixel toplami�:"+totalPixel);
			str+=totalPixel+";";
		}

		return str;
	}
	
	public static String getQuantizedPixelMagnitudeFromImageAsString(int[][] data,int qLevel,boolean isAdaptive){
		int n=256/qLevel;
		int t1=0;
		int t2=0;
		String str="";
		try {
			TBinContribution bin=new TBinContribution();
			long[] dizi=new long[n];
			for (int i = 0; i < n; i++) {
				t1=i*qLevel;
				t2=t1+qLevel;
				if (isAdaptive) {
					bin=getPixelCountWithContribution(data,t1,t2,i);
					try {
						if (i==0) {
							dizi[i]+=(long)bin.center;
							dizi[i+1]+=(long)bin.right;
						}else if(i>0 && i<n-1){
							dizi[i-1]+=(long)bin.left;
							dizi[i]+=(long)bin.center;
							dizi[i+1]+=(long)bin.right;
						}else{
							dizi[i-1]+=(long)bin.left;
							dizi[i]+=(long)bin.center;					
						}
					} catch (Exception e) {
						System.out.println("inner error:"+e.getMessage());
					}
				}else{
					long totalPixel=ImageProcess.getPixelCount(data, t1, t2);
					str+=totalPixel+";";				
				}
			}
			if (isAdaptive) {
				str="";
				for (int i = 0; i < dizi.length; i++) {
					str+=dizi[i]+";";
				}
			}
			//writeln("bin bar:"+str);
			return str;
			
		} catch (Exception e) {
			System.out.println("error:"+e.getMessage());
		}
		return str;
	}
	
	public static String getQuantizedPixelMagnitudeFromDifImageAsString(int[][] data,int qLevel){
		int n=256/qLevel;
		int t1=0;
		int t2=0;
		String str="";
		for (int i = -n; i < n; i++) {
			t1=i*qLevel;
			t2=t1+qLevel;
			long totalPixel=ImageProcess.getPixelCount(data, t1, t2);
			str+=totalPixel+";";
		}

		return str;
	}
	
	public static long getPixelSum(Image imgx) {
		int[][] temp=imageToPixels255(imgx);
		long toplam=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				toplam+=temp[i][j];
			}
		}
		return toplam;
	}
	
	/**
	 * iki treshold arasinda kalan pixellerin toplami
	 * @param orjinal image
	 * @param 1.treshold
	 * @param 2.treshold
	 * @return pixel toplami
	 */
	public static long getPixelSum(Image imgx,int thr1,int thr2) {
		int[][] temp=imageToPixels255(imgx);
		long toplam=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				if (temp[i][j]>thr1&&temp[i][j]<=thr2) {
					toplam+=temp[i][j];					
				}
			}
		}
		return toplam;
	}
	
	/**
	 * iki treshold arasinda kalan pixellerin toplaminin average i
	 * @param orjinal image
	 * @param 1.treshold
	 * @param 2.treshold
	 * @return pixel toplam average
	 */
	public static long getPixelSumAverage(Image imgx,int thr1,int thr2) {
		int[][] temp=imageToPixels255(imgx);
		long toplam=0;
		long n=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				if (temp[i][j]>thr1&&temp[i][j]<=thr2) {
					toplam+=temp[i][j];	
					n++;
				}
			}
		}
		return toplam/n;
	}
	
	/**
	 * iki treshold arasinda kalan kac pixel var
	 * @param orjinal image
	 * @param 1.treshold
	 * @param 2.treshold
	 * @return pixel sayisi
	 */
	public static long getPixelCount(Image imgx,int thr1,int thr2) {
		int[][] temp=imageToPixels255(imgx);
		long toplam=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				if (temp[i][j]>thr1&&temp[i][j]<=thr2) {
					//toplam+=temp[i][j];	
					toplam++;
				}
			}
		}
		return toplam;
	}
	/**
	 * iki treshold arasinda kalan kac pixel var
	 * @param orjinal image
	 * @param 1.treshold
	 * @param 2.treshold
	 * @return pixel sayisi
	 */
	
	public static long getPixelCount(int[][] temp,int thr1,int thr2) {
		//int[][] temp=imageToPixels255(imgx);
		long toplam=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				if (temp[i][j]>thr1&&temp[i][j]<=thr2) {
					//toplam+=temp[i][j];	
					toplam++;
				}
			}
		}
		return toplam;
	}
	
	/**
	 * iki treshold arasinda kalan adaptive binning (gaussian windowing) ile kac pixel var
	 * @param orjinal image
	 * @param 1.treshold
	 * @param 2.treshold
	 * @return pixel sayisi
	 */
	
	public static TBinContribution getPixelCountWithContribution(int[][] temp,int thr1,int thr2,int bin) {
		//int[][] temp=imageToPixels255(imgx);
		//kernel=0 ucgen
		//kernel=1 gaussian
		TBinContribution obj=new TBinContribution();
//		long toplam=0;
		for (int i = 0; i < temp.length; i++) {
			for (int j = 0; j < temp[0].length; j++) {
				if (temp[i][j]==thr1) {
					obj.center+=0.6;
					if (bin>0) {
						obj.left+=0.4;
					}
				}
				if (temp[i][j]==thr1+1) {
					obj.center+=0.7;
					if (bin>0) {
						obj.left+=0.3;
					}
				}
				if (temp[i][j]==thr1+2) {
					obj.center+=0.8;
					if (bin>0) {
						obj.left+=0.2;
					}
				}
				if (temp[i][j]==thr1+3) {
					obj.center+=0.9;
					if (bin>0) {
						obj.left+=0.1;
					}
				}
				if (temp[i][j]==thr1+4) {
					obj.center+=1;
					if (bin>0) {
						obj.left+=0;
					}
				}
				if (temp[i][j]==thr1+5) {
					obj.center+=1;
					if (bin<25) {
						obj.right+=0;
					}
				}
				if (temp[i][j]==thr1+6) {
					obj.center+=0.9;
					if (bin<25) {
						obj.right+=0.1;
					}
				}
				if (temp[i][j]==thr1+7) {
					obj.center+=0.8;
					if (bin<25) {
						obj.right+=0.2;
					}
				}
				if (temp[i][j]==thr1+8) {
					obj.center+=0.7;
					if (bin<25) {
						obj.right+=0.3;
					}
				}
				if (temp[i][j]==thr1+9) {
					obj.center+=0.6;
					if (bin<25) {
						obj.right+=0.4;
					}
				}

			}
		}
		return obj;
	}

	public static void writeToFileByFileChooser(String row,boolean isAdd) {
		JFileChooser chooser = new JFileChooser();
		chooser.setCurrentDirectory(new java.io.File("C:\\DataSet_yeni\\DS"));
		chooser.setDialogTitle("save Data Set file as");
		chooser.setSize(new java.awt.Dimension(45, 37)); // Generated
		File outFile;		
		//chooser.setSelectedFile(f);
		String activeDSDir="";
//		String currentFile="";
		if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
			File file = chooser.getSelectedFile();
			activeDSDir=file.getAbsolutePath();
//			currentFile=file.getName();
		}
		outFile = new File(activeDSDir);
		FileWriter out;
		try {
			out = new FileWriter(outFile,isAdd);
			out.write(row + "\n");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void writeToFileWithFileName(String file_name, String row,boolean isAdd) {
		File outFile = new File(file_name);
		FileWriter out;
		try {
			out = new FileWriter(outFile,isAdd);
			out.write(row + "\n");
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void writeToFile(FileWriter out, String row) {
		try {
			out.write(row + "\n");
			//out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	@SuppressWarnings("deprecation")
	public static String readFromFile(File file){
	    String ret="";
		try {
		    FileInputStream fis = null;
		    BufferedInputStream bis = null;
		    DataInputStream dis = null;
		    fis = new FileInputStream(file);
		    bis = new BufferedInputStream(fis);
		    dis = new DataInputStream(bis);

		    while (dis.available() != 0) {
		    	ret+=dis.readLine()+"\n";
		    }
		    fis.close();
		    bis.close();
		    dis.close();
	    } catch (FileNotFoundException e) {
	    	e.printStackTrace();
	    } catch (IOException e) {
	    	e.printStackTrace();
	    }
	    return ret;
	}

	public static void makeDirectory(String fileName){
		File f = new File(fileName);
		try{
		if(f.mkdir())
			System.out.println("Directory Created");
		else
			System.out.println("Directory is not created");
		}catch(Exception e){
			e.printStackTrace();
		} 
	}

	
	/*
	 * verilen bir diziyi belli bir scalara boler
	 */
	public static int[][] averageData(int[][] data,int n) {
		int[][] avgData=new int[data.length][data[0].length];
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				avgData[i][j]=(data[i][j])/n;
			}
		}
		return avgData;
	}
	
	/*
	 * parametre olarak girilen bir diziye ikinci parametreyi ekler geri gönderir
	 * 
	 */
	public static int[][] sumData(int[][] globalData, int[][] data) {
		if (globalData==null) {
			globalData=new int[data.length][data[0].length];
		}
		int[][] retData=new int[data.length][data[0].length];
		int m=0,n=0;
		try {
			for (int i = 0; i < data.length; i++) {
				for (int j = 0; j < data[0].length; j++) {
					m=i;
					n=j;
					retData[i][j]=globalData[i][j]+data[i][j];
				}
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println(m+":"+n);
		}
		return retData;
	}

	
	/*
	 * Verilen bir image dizisinin averajini geri donderir. 
	 * Hatali olabilir dikkatli kullanilsin
	 */
	public static Image getAverageImage(Image[] imgs) {
		int n=imgs.length;
		int[][] total=null;//new int[temp.length][temp[0].length];
		for (int i = 0; i < imgs.length; i++) {
			int[][] data=imageToPixels255(imgs[i]);
			total=sumData(total, data); 
		}
		total=averageData(total, n);
		Image ret=pixelsToImage255(total);
		return ret;
	}

	public static int[][] imageAbsoluteRatioArray(Image img1,Image img2) {
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int temp[][]=new int[w1][h1];
		int[][] dizi1=imageToPixels255(img1);
		int[][] dizi2=imageToPixels255(img2);
		
		double ratio=0;
		int x1,x2;
		//int k=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				x1=dizi1[i][j];
				x2=dizi2[i][j];
				if (x1==0) {
					x1=1;
				}
				if (x2==0) {
					x2=1;
				}
				if (x1<x2) {
					ratio=(x2*1.0)/(x1*1.0);
				}
				else{
					ratio=(x1*1.0)/(x2*1.0);
				}
				int a=(int)Math.round(ratio*10);
				if (a>255) {
					a=255;
					//k++;
					//writeln(k+". 255 den buyuk olma durumu");
				}
				temp[i][j]=a;
				//fark=Math.abs(dizi1[i][j]-dizi2[i][j]);
				//fark=(dizi1[i][j]-dizi2[i][j]);
//				if (ratio>0&&ratio<=255) {
//					temp[i][j]=ratio;	
//				}else{
//					temp[i][j]=0;
//				}
			}
		}		
		return temp;
	}

	public static Image imageAbsoluteRatio(Image img1, Image img2) {
		return pixelsToImage255(imageAbsoluteRatioArray(img1,img2));
	}
	
	public static Image getTeagerEnergyImage(Image img, Image imgL, Image imgR) {
		int[][] d=imageToPixels255(img);
		int[][] dL=imageToPixels255(imgL);
		int[][] dR=imageToPixels255(imgR);
		int[][] ret=new int[d.length][d[0].length];
		for (int i = 0; i < ret.length; i++) {
			for (int j = 0; j < ret[0].length; j++) {
				int a=d[i][j];
				int b=dL[i][j];
				int c=dR[i][j];
				
				int x=(Math.abs(a*a-b*c));
//				if (x>255) {
//					x=255;
//				}
				//int x=(int)Math.sqrt(Math.abs(a*a-b*c));
				//int x=(int)Math.log10(Math.abs(a*a-b*c));
				ret[i][j]=x;
			}
		}
		return pixelsToImage255(ret);
	}

	public static double getTeagerEnergyMean(Image img, Image imgL, Image imgR) {
		int[][] d=imageToPixels255(img);
		int[][] dL=imageToPixels255(imgL);
		int[][] dR=imageToPixels255(imgR);
		double mC=Utils.getMean(d);
		double mL=Utils.getMean(dL);
		double mR=Utils.getMean(dR);
		double ret=Utils.formatDouble(mC*mC-mL*mR);
		return ret;
	}

	public static double getTeagerEnergyPixel(Image img, Image imgL, Image imgR) {
		int[][] d=imageToPixels255(img);
		int[][] dL=imageToPixels255(imgL);
		int[][] dR=imageToPixels255(imgR);
		double ret=0;
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				double t=d[i][j]*d[i][j]-dL[i][j]*dR[i][j];
				ret+=t;
			}
		}
		return ret;
	}
	
	public static double getTeagerEnergyAbsolutePixelExposureNormalized(Image img, Image imgL, Image imgR,int n,String type) {
		int[][] d=imageToPixels255(img);
		int[][] dL=imageToPixels255(imgL);
		int[][] dR=imageToPixels255(imgR);
		
		if (type.equals("halogen")) {
			if(n>=0 && n<9){
				
			}else if(n==9){
				dR=normalizeArrayWithExposure(5,dR);
			}else if(n==10){
				d=normalizeArrayWithExposure(5,d);
				dR=normalizeArrayWithExposure(5,dR);				
			}else if(n>=11 && n<19){
				d=normalizeArrayWithExposure(5,d);
				dL=normalizeArrayWithExposure(5,dL);				
				dR=normalizeArrayWithExposure(5,dR);				
			}else if(n==19){
				dR=normalizeArrayWithExposure(9,dR);
			}else if(n==20){
				d=normalizeArrayWithExposure(9,d);
				dR=normalizeArrayWithExposure(9,dR);				
			}else{
				d=normalizeArrayWithExposure(9,d);
				dL=normalizeArrayWithExposure(9,dL);				
				dR=normalizeArrayWithExposure(9,dR);				
			}
		}
		if (type.equals("uv")) {
			if(n>=0 && n<29){
				
			}else if(n==29){
				dR=normalizeArrayWithExposure(3,dR);
			}else if(n==30){
				d=normalizeArrayWithExposure(3,d);
				dR=normalizeArrayWithExposure(3,dR);				
			}else {
				d=normalizeArrayWithExposure(3,d);
				dL=normalizeArrayWithExposure(3,dL);				
				dR=normalizeArrayWithExposure(3,dR);				
			}
		}

		double ret=0;
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				double t=Math.abs(d[i][j]*d[i][j]-dL[i][j]*dR[i][j]);
				ret+=t;
			}
		}
		double size=d.length*d[0].length;
		return Utils.formatDouble(ret/size);
	}

	public static double getTeagerEnergyAbsolutePixel(Image img, Image imgL, Image imgR,int n,String type) {
		int[][] d=imageToPixels255(img);
		int[][] dL=imageToPixels255(imgL);
		int[][] dR=imageToPixels255(imgR);
		double ret=0;
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				double t=Math.abs(d[i][j]*d[i][j]-dL[i][j]*dR[i][j]);
				ret+=t;
			}
		}
		double size=d.length*d[0].length;
		return Utils.formatDouble(ret/size);
	}
	
	/**
	 * herhangi bir image 2D datasinin icinde herhangi bir pixel degerinin
	 * image uzerindeki pozisyonunun listesini verir.
	 * @param avgData
	 * @param i
	 * @return
	 */
	public static ArrayList<Point> getPixelPositionList(int[][] data, int p) {
		ArrayList<Point> ret=new ArrayList<Point>();
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				if (data[i][j]==p) {
					ret.add(new Point(i,j));
				}
			}
		}
		return ret;
	}

	
	/**
	 * Parametre olarak girilen bir imgenin histogramini equalize etmeye yarar
	 * @param img_avg
	 * @return histogrami equalize edilmis image 
	 */
	public static Image getHistogramEqualizedImage(Image img) {
		int[][] data=imageToPixels255(img);
		int[][] retData=new int[data.length][data[0].length];
		int[] cumHist=getCumulativeHistogramData(data);
		int numPix=(data.length*data[0].length);
		double alpha=255.0/numPix;
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				retData[i][j]=(int)(cumHist[data[i][j]]*alpha);
			}
		}
		Image retImg=pixelsToImage255(retData);
		return retImg;
	}
	
	public static int[] getHistogramData(int[][] data){
		int[] histogram = new int[256];
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				histogram[data[i][j]]++;
			}
		}
		return histogram;
	}
	
	public static int[] getCumulativeHistogramData(int[][] data){
		int[] hist=getHistogramData(data);
		int[] cumulativeHist = new int[256];
		int total=0;
		for (int i = 0; i < 256; i++) {
			total+=hist[i];
			cumulativeHist[i]=total;
		}
		return cumulativeHist;
	}

	/**
	 * Hyperspectral image kupun n. bandinda bir bolgenin average degerini hesaplar
	 * @param fullData
	 * @param i
	 * @param p1
	 * @param p2
	 * @return
	 */
	public static int getROIMeanValue(short[][][] fullData, int n, Point p1, Point p2) {
		// TODO Auto-generated method stub
		int total=0;
		int k=0;
		for (int i = p1.x; i < p2.x; i++) {
			for (int j =p1.y; j < p2.y; j++) {
				k++;
				total+=fullData[n][i][j];
			}
		}
		int ret=total/k;
		return ret;
	}

	
	public int[] imageDifferenceSignatureFrequency(Image img1, Image img2,int delta) {
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		int w2=img2.getWidth(null);
		int h2=img2.getHeight(null);
		int dizi2[][]=new int[w2][h2];		
		int temp[]=new int[delta+1];
		dizi1=imageToPixels255(img1);
		dizi2=imageToPixels255(img2);
		
		int fark=0;
		for (int i = 0; i < w1; i++) {
			for (int j = 0; j < h1; j++) {
				fark=dizi2[i][j]-dizi1[i][j];
				//negative index olmadigindan dolayi negative olanlar delta/2 den cikarilip
				//yani tersleyip 0 index ten itibaren diziye yazilir.
				//normalde 0 ve 0'dan buyuk frekanslar da delta/2 eklenerek yeni yerlerine shift edilir. 
				if (fark>=0 && Math.abs(fark)+delta/2<=delta) {
					temp[Math.abs(fark)+delta/2]++;
				}else if(fark<0 && Math.abs(fark)<=delta/2){
					temp[delta/2-Math.abs(fark)]++;
				}
			}
		}		
		return temp;
	}

	public static String getArrayAsString(int[] ret) {
		String str="";
		for (int i = 0; i < ret.length; i++) {
			str+=ret[i]+";";
		}
		return str;
	}

	
	public int getTotal(int[][] data) {
		int toplam=0;
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[0].length; j++) {
				toplam+=data[i][j];
			}
		}
		return toplam;
	}

	public static int[][] imageIndividualArrayWithNormalization(Image img1,int n,String type){
		int w1=img1.getWidth(null);
		int h1=img1.getHeight(null);
		int dizi1[][]=new int[w1][h1];
		dizi1=imageToPixels255(img1);
		if (type.equals("halogen")) {
			if(n>=0 && n<9){
				
			}else if(n>=9 && n<19){
				dizi1=normalizeArrayWithExposure(4.5/2.4,dizi1);
			}else{
				dizi1=normalizeArrayWithExposure(4.5/0.5,dizi1);
			}
		}
		if (type.equals("uv")) {
			if(n>=0 && n<29){
				
			}else {
				dizi1=normalizeArrayWithExposure(9.6/3.1,dizi1);
			}
		}
		return dizi1;
	}

	public static int[][] transformImageByPower(int[][] d, double e,double c) {
		for (int i = 0; i < d.length; i++) {
			for (int j = 0; j < d[0].length; j++) {
				//d[i][j]=(int)(c*(int)Math.pow(d[i][j],e));
				if (d[i][j]>0) {
					d[i][j]=(int)((int)Math.pow(d[i][j],e))+(int)c;
				}else{
					d[i][j]=(int)((int)Math.pow(d[i][j],e));
				}
				
			}
		}
		return d;
	}

	public static String getNormalDiffQuantizedPixelMagnitudeFromDifImageAsString(int[][] data, int qLevel) {
		int n=256/qLevel;
		int t1=0;
		int t2=0;
		String str="";
		for (int i = -n; i < n; i++) {
			t1=i*qLevel;
			t2=t1+qLevel;
			long totalPixel=ImageProcess.getPixelCount(data, t1, t2);
			str+=totalPixel+";";
		}
		return str;
	}


	
}
